package com.ns.sbs.oauth.role4permission.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ns.sbs.oauth.rent.mapper.RentPermissionMapper;
import com.ns.sbs.oauth.role.mapper.RoleMapper;
import com.ns.sbs.oauth.role4permission.entry.RolePermission;
import com.ns.sbs.oauth.role4permission.mapper.RolePermissionMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色权限中间表
 *
 * @author lw
 */
@Service
@RequiredArgsConstructor
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements IRolePermissionService {

    private final RolePermissionMapper rolePermissionMapper;

    private final RoleMapper roleMapper;
    private final RentPermissionMapper rentPermissionMapper;

    /**
     * 获取指定角色的所有权限码 【增加缓存】
     */
    @Override
    public List<Long> getCodeByRoleId(Long roleId) {
        return rolePermissionMapper.getCodeByRoleId(roleId);
    }

    /**
     * [T] 修改角色的一组权限关系 【清除缓存 】
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateRoleMenu(Long roleId, List<String> permissions) {
        // 万一为空
        if (permissions == null) {
            permissions = new ArrayList<>();
        }
        // 先删
        rolePermissionMapper.deleteByRoleId(roleId);
        // 再添加
        List<RolePermission> list = new ArrayList<>();
        for (String id : permissions) {
            RolePermission p = new RolePermission();
            p.setRoleId(roleId);
            p.setPermission(Long.parseLong(id));
            list.add(p);
        }
        rolePermissionMapper.insert(list);
        // 返回
        return permissions.size();
    }
}
